package com.android.questions.ui.fragment;

import android.annotation.SuppressLint;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Looper;
import android.text.Html;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.viewbinding.ViewBinding;

import com.android.base.ui.base.VBBaseFragment;
import com.android.base.util.ActivityClickUtil;
import com.android.base.util.DQLog;
import com.android.base.util.Mmkv;
import com.android.base.util.NumberFormatUtil;
import com.android.base.util.ToastUtil;
import com.android.questions.R;
import com.android.questions.config.AnswerAdConfig;
import com.android.questions.config.AppConfig;
import com.android.questions.config.AppDataSourse;
import com.android.questions.config.LoginConfig;
import com.android.questions.databinding.FragmentHomeRunBinding;
import com.android.questions.entity.AnswerEntity;
import com.android.questions.litepal.AnswerLitePalEntity;
import com.android.questions.ui.activity.IntroduceActivity;
import com.android.questions.ui.activity.MainActivity;
import com.android.questions.ui.activity.SettingActivity;
import com.android.questions.ui.adapter.HomeRunAdapter;
import com.android.questions.ui.dialog.DialogAddCoinResult;
import com.android.questions.ui.dialog.DialogAnswerAssistant;
import com.android.questions.ui.dialog.DialogAnswerCorrect;
import com.android.questions.ui.dialog.DialogAnswerFailure;
import com.android.questions.ui.dialog.DialogBanned;
import com.android.questions.ui.dialog.DialogCashCow;
import com.android.questions.ui.dialog.DialogDailyWithdrawal;
import com.android.questions.ui.dialog.DialogGoWithdrawal;
import com.android.questions.ui.dialog.DialogGuide;
import com.android.questions.ui.dialog.DialogHpTip;
import com.android.questions.ui.dialog.DialogInvite;
import com.android.questions.ui.dialog.DialogLuckyCircle;
import com.android.questions.ui.dialog.DialogRedBubble;
import com.android.questions.ui.dialog.DialogSaveCash;
import com.android.questions.ui.dialog.DialogShare;
import com.android.questions.ui.dialog.DialogSign;
import com.android.questions.ui.dialog.DialogSwitchAnswer;
import com.android.questions.ui.dialog.DialogSwitchProgress;
import com.android.questions.ui.dialog.DialogUnlockAnswer;
import com.android.questions.util.AnimUtil;
import com.android.questions.util.Command;
import com.android.questions.util.GuideComponent;
import com.android.questions.util.LotteryUtil;
import com.android.questions.util.sound.FailureMusicManager;
import com.android.questions.util.sound.GameMusicManager;
import com.android.questions.util.sound.GoldMusicManager;
import com.android.questions.util.sound.MediaBackManager;
import com.android.questions.util.sound.VictoryMusicManager;
import com.binioter.guideview.Guide;
import com.binioter.guideview.GuideBuilder;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.dq.ad.AdManager;
import com.dq.ad.UMManager;
import com.dq.ad.dialog.BaseAdDialogLoading;
import com.hx.currency.HXCurrencySDK;
import com.hx.currency.data.api.SignConfigResp;
import com.hx.currency.data.api.SignResp;
import com.hx.currency.data.qa.api.QAAnswerStatisticsResp;
import com.hx.currency.data.qa.api.QADoubleRewardResp;
import com.hx.currency.data.qa.api.QAWatchVideoResp;
import com.hx.currency.data.qa.model.QAPrize;
import com.hx.update.utils.UpdateUtil;
import com.qq.e.o.ads.v2.error.AdError;
import com.qq.e.o.data.HttpUtil;
import com.qq.e.o.utils.JsonUtil;

import org.litepal.LitePal;

import java.util.ArrayList;
import java.util.List;

/**
 * FileName: HomeRunFragment
 * Author: admin
 * Date: 2021/11/2 9:26
 * Description:
 */
public class HomeRunFragment extends VBBaseFragment implements HomeRunAdapter.OnItemClickLister, View.OnClickListener {

    private FragmentHomeRunBinding runBinding;
    private AnswerEntity.DataBean dataBean;
    private MainActivity mainActivity;
    private HomeRunAdapter runAdapter;
    private boolean isReward = false;
    private DialogAddCoinResult dialogAddCoinResult = null;
    private DialogSwitchAnswer dialogSwitchAnswer = null;
    private DialogUnlockAnswer dialogUnlockAnswer = null;
    private DialogAnswerCorrect dialogAnswerCorrect = null;
    private DialogAnswerFailure dialogAnswerFailure = null;
    private BaseAdDialogLoading dialogLoading = null;
    private AnswerLitePalEntity litePalEntity = null;
    private int answerType = 1;
    private int rightIndex = -1;

    private Handler mHandler = null;

    private long bubbleTime1 = 0;
    private long bubbleTime2 = 0;
    private long bubbleTime3 = 0;
    private int saveCountTime = 0;
    private boolean isGetSaveCash = false;//有金币进入存钱罐后，播放金币飞向存钱罐动画
    private boolean isAnswerSending = false;//答题结果是否上报中，上报中不能再次点击答题

    public static HomeRunFragment createFragment() {
        return new HomeRunFragment();
    }

    @Override
    protected ViewBinding getViewBinding(LayoutInflater inflater) {
        return runBinding = FragmentHomeRunBinding.inflate(inflater);
    }

    @Override
    public void onSupportVisible() {
        super.onSupportVisible();
        setTitleBackground(BG_WHITE);

        if (AppConfig.isGoonMakeMoney) {
            AppConfig.isGoonMakeMoney = false;
            UMManager.onEvent(UMManager.Event.WithdrawalsHongbao_eject);
            new DialogAnswerAssistant(activity).setClickLister(new DialogAnswerAssistant.OnClickLister() {
                @Override
                public void onNext() {
                    watchVideo();
                }
            }).show();
        }
        updateCoinInfo();
    }

    private void updateCoinInfo() {
        // 红包券数量
        String format = NumberFormatUtil.convertDoubleToString(LoginConfig.getUserCash() * LoginConfig.getCashConvert()) + "元";
        runBinding.tvCashMoney.setText(format);

        // 摇钱树金额
        String cowCash = NumberFormatUtil.convertDoubleToString(AppConfig.getCashCow()) + "元";
        runBinding.tvCowCash.setText(cowCash);
    }

    @Override
    public void onSupportInvisible() {
        super.onSupportInvisible();
    }

    @Override
    public void initView() {
        super.initView();
        mainActivity = (MainActivity) activity;
        runAdapter = new HomeRunAdapter();
        runBinding.recyclerView.setLayoutManager(Command.Method.getLinearLayoutManager(activity, false));
        runBinding.recyclerView.setAdapter(runAdapter);

        updateUI();

        initBubble();//红包气泡
        initSaveCash();//存钱罐
        initHp();//体力

        if (mHandler == null) {
            mHandler = new Handler();
            Runnable r = new Runnable() {
                @Override
                public void run() {
                    if (activity.isFinishing()) {
                        return;
                    }
                    updateBubbleVisible();
                    handlerSaveCashPerSec();
                    handlerHpPerSec();

                    //每隔1s循环执行run方法
                    mHandler.postDelayed(this, 1000);
                }
            };
            mHandler.postDelayed(r, 1000);
        }

//        new DialogBanned(activity).setTitle("先休息休息").setClickLister(() -> activity.finish()).show();
//        new DialogWithError(activity).setType(DialogWithError.TYPE_TIPS).setNum(10).setTipStr("请先完成上一条提现").show();
//        new DialogWithdrawalSuccess(activity).setQueue(true).setCash(100).show();
//        new DialogShare(activity).show();
//        new DialogRedBubble(activity).setType(DialogRedBubble.TYPE_SURPRISE).show();
//        new DialogInvite(activity).show();
//        new DialogGoWithdrawal(activity).setCoin(100).setType(1).show();
//        new DialogAddCoin(activity).show();
//        new DialogGuide(activity).setType(DialogGuide.TYPE_TIPS).show();
//        new DialogJointQQ(activity).show();

        if (AppConfig.updateInfo != null) {
            UpdateUtil.checkUpdate(activity, AppConfig.updateInfo, new UpdateUtil.OnUpdateCallback() {
                @Override
                public void onCancel() {
                    showGuideDialog();
                }
            });
        } else {
            showGuideDialog();
        }
    }

    public void showGuideView(TextView view) {
        ViewGroup.LayoutParams params =
                new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                        ViewGroup.LayoutParams.MATCH_PARENT);
        View blackMask = new View(activity);
        blackMask.setLayoutParams(params);
        blackMask.setBackgroundColor(activity.getResources().getColor(R.color.Color_000000));
        blackMask.setAlpha(0.7f);
        runBinding.getRoot().addView(blackMask);

        runBinding.scrollView.bringToFront();

        GuideBuilder builder = new GuideBuilder();
        builder.setTargetView(view).setAutoDismiss(false)
                .setAlpha(0)
                .setHighTargetCorner(50)
                .setHighTargetPaddingLeft(45)
                .setHighTargetPaddingRight(45)
                .setHighTargetPaddingTop(20)
                .setHighTargetPaddingBottom(20);
        builder.setOnVisibilityChangedListener(new GuideBuilder.OnVisibilityChangedListener() {
            @Override
            public void onShown() {
            }

            @Override
            public void onDismiss() {

            }
        });

        GuideComponent comp = new GuideComponent();
        builder.addComponent(comp);
        Guide guide = builder.createGuide();
        comp.setGuideClickLister(new GuideComponent.OnGuideClickLister() {
            @Override
            public void onGuideClick() {
                onItemClick(rightIndex, view);
                LoginConfig.setGuideIndex(1);

                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        guide.dismiss();
                        blackMask.setVisibility(View.GONE);

                        ViewGroup parent = (ViewGroup) runBinding.scrollView.getParent();
                        parent.removeView(runBinding.scrollView);
                        parent.addView(runBinding.scrollView, 1);
                        parent.requestLayout();
                        parent.invalidate();

                        if (bubbleTime1 == 0) {
                            AnimUtil.upDownAnim(activity, runBinding.btnRedBubble1);
                        } else {
                            runBinding.btnRedBubble1.setVisibility(View.GONE);
                        }

                        if (bubbleTime2 == 0) {
                            AnimUtil.upDownAnim(activity, runBinding.btnRedBubble2);
                        } else {
                            runBinding.btnRedBubble2.setVisibility(View.GONE);
                        }

                        if (bubbleTime3 == 0) {
                            AnimUtil.upDownAnim(activity, runBinding.btnRedBubble3);
                        } else {
                            runBinding.btnRedBubble3.setVisibility(View.GONE);
                        }
                    }
                }, 600);
            }
        });
        guide.show(activity);
    }

    private void initBubble() {
        if (LoginConfig.getRedBubbleTimes() >= AppConfig.BUBBLE_TIMES_MAX) {
            bubbleTime1 = 0;
            bubbleTime2 = 0;
            bubbleTime3 = 0;
            runBinding.btnRedBubble1.setVisibility(View.GONE);
            runBinding.btnRedBubble2.setVisibility(View.GONE);
            runBinding.btnRedBubble3.setVisibility(View.GONE);
            return;
        }

        bubbleTime1 = Mmkv.getLong("bubbleTime1");
        bubbleTime2 = Mmkv.getLong("bubbleTime2");
        bubbleTime3 = Mmkv.getLong("bubbleTime3");

        if (bubbleTime1 == 0) {
            AnimUtil.upDownAnim(activity, runBinding.btnRedBubble1);
        } else {
            runBinding.btnRedBubble1.setVisibility(View.GONE);
        }

        if (bubbleTime2 == 0) {
            AnimUtil.upDownAnim(activity, runBinding.btnRedBubble2);
        } else {
            runBinding.btnRedBubble2.setVisibility(View.GONE);
        }

        if (bubbleTime3 == 0) {
            AnimUtil.upDownAnim(activity, runBinding.btnRedBubble3);
        } else {
            runBinding.btnRedBubble3.setVisibility(View.GONE);
        }

        updateBubbleVisible();
    }

    private void updateBubbleVisible() {
        if (bubbleTime1 != 0) {
            long curTime = System.currentTimeMillis();
            if (curTime - bubbleTime1 >= 60000) {
                bubbleTime1 = 0;
                Mmkv.setLong("bubbleTime1", bubbleTime1);
                AnimUtil.upDownAnim(activity, runBinding.btnRedBubble1);
                runBinding.btnRedBubble1.setVisibility(View.VISIBLE);
            }
        }

        if (bubbleTime2 != 0) {
            long curTime = System.currentTimeMillis();
            if (curTime - bubbleTime2 >= 60000) {
                bubbleTime2 = 0;
                Mmkv.setLong("bubbleTime2", bubbleTime2);
                AnimUtil.upDownAnim(activity, runBinding.btnRedBubble2);
                runBinding.btnRedBubble2.setVisibility(View.VISIBLE);
            }
        }

        if (bubbleTime3 != 0) {
            long curTime = System.currentTimeMillis();
            if (curTime - bubbleTime3 >= 60000) {
                bubbleTime3 = 0;
                Mmkv.setLong("bubbleTime3", bubbleTime3);
                AnimUtil.upDownAnim(activity, runBinding.btnRedBubble3);
                runBinding.btnRedBubble3.setVisibility(View.VISIBLE);
            }
        }
    }

    private void initSaveCash() {
        runBinding.tvSaveCashNum.setText((int) LoginConfig.getSaveCash() + "");

        if (AppConfig.saveCashState == 1) {
            runBinding.ivTipGetBg.setAlpha(1f);
        } else {
            runBinding.ivTipGetBg.setAlpha(0f);
        }
        runBinding.tvSaveCashNum.setAlpha(0f);
        runBinding.ivTipsIcon.setAlpha(0f);
        runBinding.ivTipNumBg.setAlpha(0f);

        saveCountTime = 20;
    }

    public void handlerSaveCashPerSec() {
        if (AppConfig.saveCashState == 0) {
            if (saveCountTime == 0) {
                runBinding.ivTipNumBg.animate().alpha(1f).setDuration(300);
                runBinding.ivTipsIcon.animate().alpha(1f).setDuration(300);
                runBinding.tvSaveCashNum.animate().alpha(1f).setDuration(300);
            } else if (saveCountTime == 4) {
                runBinding.ivTipNumBg.animate().alpha(0f).setDuration(300);
                runBinding.ivTipsIcon.animate().alpha(0f).setDuration(300);
                runBinding.tvSaveCashNum.animate().alpha(0f).setDuration(300);
            } else if (saveCountTime == 30) {
                saveCountTime = -1;
            }
            saveCountTime++;
        }
    }

    private void initHp() {
        runBinding.tvHp.getPaint().setFakeBoldText(true);
        runBinding.tvHp.setText(AppConfig.hp + "");

        updateHpTime();
    }

    private void updateHpTime() {
        if (AppConfig.hp >= AppConfig.FHP) {
            runBinding.tvHpTime.setText("已满");
        } else {
            runBinding.tvHpTime.setText(String.format("%d:%02d", AppConfig.ahp / 60, AppConfig.ahp % 60));
        }
    }

    /**
     * 加一点体力
     */
    private void addOneHp() {
        AppConfig.hp++;
        if (AppConfig.hp >= AppConfig.FHP) {
            AppConfig.hp = AppConfig.FHP;
            runBinding.tvHpTime.setText("已满");
        }
        runBinding.tvHp.setText(AppConfig.hp + "");
    }

    /**
     * 扣一点体力
     */
    private void reduceOneHp() {
        if (AppConfig.hp == AppConfig.FHP) {
            AppConfig.ahp = AppConfig.UHP + 1;//如果满体力,重置倒计时时间
        }
        AppConfig.hp--;
        runBinding.tvHp.setText(AppConfig.hp + "");
    }

    private void handlerHpPerSec() {
        if (AppConfig.hp < AppConfig.FHP) {
            AppConfig.ahp--;
            if (AppConfig.ahp < 0) {
                AppConfig.hp++;
                runBinding.tvHp.setText(AppConfig.hp + "");
                AppConfig.ahp = AppConfig.UHP;
            }

            updateHpTime();
        }
    }

    @Override
    public void initLister() {
        super.initLister();
        runAdapter.setOnItemClickLister(this);
        runAdapter.setGuideLister(new HomeRunAdapter.OnGuideLister() {
            @Override
            public void onGuideView(int position, TextView tvAnswer) {
                if (position == rightIndex) {
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            showGuideView(tvAnswer);
                        }
                    }, 100);
                }
            }
        });

        runBinding.imgSetting.setOnClickListener(this);
        runBinding.ivWallet.setOnClickListener(this);
        runBinding.imgWithdrawal.setOnClickListener(this);
        runBinding.ivCowWithdrawal.setOnClickListener(this);

        runBinding.clSign.setOnClickListener(this);
        runBinding.clLucky.setOnClickListener(this);
        runBinding.clInvite.setOnClickListener(this);
        runBinding.clDailyTask.setOnClickListener(this);
        runBinding.clPush.setOnClickListener(this);
        runBinding.clSwitchAnswer.setOnClickListener(this);

        runBinding.btnRedBubble1.setOnClickListener(this);
        runBinding.btnRedBubble2.setOnClickListener(this);
        runBinding.btnRedBubble3.setOnClickListener(this);

        runBinding.btnSaveCash.setOnClickListener(this);
        runBinding.layoutHp.setOnClickListener(this);
    }

    private final CountDownTimer countDownTimer = new CountDownTimer(3000L, 1000L) {
        @Override
        public void onTick(long millisUntilFinished) {

        }

        @Override
        public void onFinish() {
            updateOptions();
        }
    };

    private void updateOptions() {
//        DQLog.e("rightIndex: " + rightIndex);
        runAdapter.setRightIndex(rightIndex);
        runAdapter.notifyDataSetChanged();
    }

    @SuppressLint("SetTextI18n")
    private void updateUI() {
        if (activity.isFinishing()) return;

        if (LoginConfig.getTodaySignState() == 0) {
            runBinding.tvSignTips.setText("今日待签到");
            runBinding.tvSignTips.setVisibility(View.VISIBLE);
        } else {
            runBinding.tvSignTips.setVisibility(View.GONE);
        }

        List<AnswerLitePalEntity> litePalEntityList = null;
        answerType = AppConfig.getAnswerType();
        DQLog.e("answerType -> " + answerType);
        if (answerType == 1) {
            litePalEntityList = LitePal.where("answerType==1").find(AnswerLitePalEntity.class);
        } else if (answerType == 2) {
            litePalEntityList = LitePal.where("answerType==2").find(AnswerLitePalEntity.class);
        } else if (answerType == 3) {
            litePalEntityList = LitePal.where("answerType==3").find(AnswerLitePalEntity.class);
        } else if (answerType == 4) {
            litePalEntityList = LitePal.where("answerType==4").find(AnswerLitePalEntity.class);
        } else if (answerType == 5) {
            litePalEntityList = LitePal.where("answerType==5").find(AnswerLitePalEntity.class);
        } else if (answerType == 6) {
            litePalEntityList = LitePal.where("answerType==6").find(AnswerLitePalEntity.class);
        }

        if (litePalEntityList == null || litePalEntityList.size() == 0) {
            DQLog.e("litePalEntityList == null");
            return;
        }
        litePalEntity = litePalEntityList.get(0);

        List<AnswerEntity.DataBean> beans = AppDataSourse.getAnswerData(litePalEntity);
        if (beans == null || beans.size() <= 0) {
            return;
        }

        if (litePalEntity.getAnswerPosition() >= beans.size()) {
            litePalEntity.setAnswerRound(litePalEntity.getAnswerRound() + 1);
            litePalEntity.save();
            beans = AppDataSourse.getAnswerData(litePalEntity);
        }

        updateCoinInfo();

        if (LoginConfig.getUserCash() >= 3000) {
            runBinding.ivWallet.setImageResource(R.drawable.icon_fragment_home_run_wallet_2);
            AnimUtil.receiveAnim(activity, runBinding.ivWallet);
        } else {
            runBinding.ivWallet.setImageResource(R.drawable.icon_fragment_home_run_wallet_1);
        }

        int totalNumber;
        if (AppConfig.getExtractTimes() < 1) {
            totalNumber = AppConfig.GEAR_WITHDRAWAL[0];
        } else {
            totalNumber = AppConfig.GEAR_WITHDRAWAL[1];
        }
        String dailyTaskTips;
        int cha = totalNumber - AppConfig.getDayAnswerNumber();
        if (cha > 0) {
            dailyTaskTips = "<font color='#F7F263'>" + cha + "</font>题后可提现";
        } else {
            dailyTaskTips = "可提现";
        }
        runBinding.tvDailyTaskTips.setText(Html.fromHtml(dailyTaskTips));

        dataBean = beans.get(litePalEntity.getAnswerPosition());

        String answerType = "当前题库：<font color='#FDF61E'>" + litePalEntity.getTypeName() + "</font>";
        runBinding.tvAnswerType.setText(Html.fromHtml(answerType));

        List<String> stringList = new ArrayList<>();
        if (!TextUtils.isEmpty(dataBean.getAnswerA())) {
            stringList.add(dataBean.getAnswerA());
        }
        if (!TextUtils.isEmpty(dataBean.getAnswerB())) {
            stringList.add(dataBean.getAnswerB());
        }
        if (!TextUtils.isEmpty(dataBean.getAnswerC())) {
            stringList.add(dataBean.getAnswerC());
        }
        if (!TextUtils.isEmpty(dataBean.getAnswerD())) {
            stringList.add(dataBean.getAnswerD());
        }

        String answer = dataBean.getAnswer();
        if ("A".equals(answer)) {
            rightIndex = 0;
        } else if ("B".equals(answer)) {
            rightIndex = 1;
        } else if ("C".equals(answer)) {
            rightIndex = 2;
        } else if ("D".equals(answer)) {
            rightIndex = 3;
        }

        countDownTimer.cancel();
        countDownTimer.start();

        String answerSum = "第 <font color='#FD001A'>" + (LoginConfig.getUserAnswerNumber() + 1) + "</font> 题";
        runBinding.tvAnswerSum.setText(Html.fromHtml(answerSum));

        String haveSum = "答对：<font color='#FD001A'>" + LoginConfig.getUserAnswerSuccessNumber() + "</font>";
        runBinding.tvHaveSum.setText(Html.fromHtml(haveSum));

        String correct;
        if (LoginConfig.getUserAnswerNumber() > 0) {
            correct = "答题正确率:<font color='#FD001A'>" + (LoginConfig.getUserAnswerSuccessNumber() * 100 / LoginConfig.getUserAnswerNumber()) + "%</font>";
        } else {
            correct = "答题正确率:<font color='#FD001A'>" + 0 + "%</font>";
        }
        runBinding.tvCorrect.setText(Html.fromHtml(correct));

        if (runAdapter != null) {
            DQLog.e("runAdapter != null");
            runAdapter.setList(stringList);
        } else {
            runAdapter = new HomeRunAdapter();
            runBinding.recyclerView.setLayoutManager(Command.Method.getLinearLayoutManager(activity, false));
            runBinding.recyclerView.setAdapter(runAdapter);
            runAdapter.setList(stringList);

            runAdapter.setAnimationWithDefault(BaseQuickAdapter.AnimationType.SlideInRight);
        }

        if (LoginConfig.getUserAnswerSuccessNumber() == 1) {
            UMManager.onEvent(UMManager.Event.answers_CG_1);
        } else if (LoginConfig.getUserAnswerSuccessNumber() == 5) {
            UMManager.onEvent(UMManager.Event.answers_CG_5);
        } else if (LoginConfig.getUserAnswerSuccessNumber() == 10) {
            UMManager.onEvent(UMManager.Event.answers_CG_10);
        } else if (LoginConfig.getUserAnswerSuccessNumber() == 20) {
            UMManager.onEvent(UMManager.Event.answers_CG_20);
        } else if (LoginConfig.getUserAnswerSuccessNumber() == 30) {
            UMManager.onEvent(UMManager.Event.answers_CG_30);
        } else if (LoginConfig.getUserAnswerSuccessNumber() == 50) {
            UMManager.onEvent(UMManager.Event.answers_CG_50);
        } else if (LoginConfig.getUserAnswerSuccessNumber() == 100) {
            UMManager.onEvent(UMManager.Event.answers_CG_100);
        } else if (LoginConfig.getUserAnswerSuccessNumber() == 200) {
            UMManager.onEvent(UMManager.Event.answers_CG_200);
        }

        String titleStr = dataBean.getTitle();
        DQLog.e("titleStr: " + titleStr);
        String title = titleStr.substring(0, titleStr.indexOf("["));
        DQLog.e("title: " + title);
        String indexStr = titleStr.substring(titleStr.indexOf("[") + 1, titleStr.indexOf("]"));
        int index = Integer.parseInt(indexStr);
        DQLog.e("index: " + index);
        String str = titleStr.substring(index, index + 1);
        title = title.replaceAll(str, "__");
        DQLog.e("title: " + title);

        runBinding.tvAnswerName.setTextSize(TypedValue.COMPLEX_UNIT_SP, 20);
        runBinding.tvAnswerName.setText(title);

//        if (!AppConfig.isShowDaily1() && AppConfig.getDayAnswerNumber() == AppConfig.GEAR_WITHDRAWAL[0]) {
//            AppConfig.setShowDaily1(true);
//            showDailyDialog();
//        }
//        if (!AppConfig.isShowDaily2() && AppConfig.getDayAnswerNumber() == AppConfig.GEAR_WITHDRAWAL[1]) {
//            AppConfig.setShowDaily2(true);
//            showDailyDialog();
//        }

        updateHpTime();
        runBinding.tvHp.setText(AppConfig.hp + "");
    }

    @Override
    public void onItemClick(int position, TextView tvAnswer) {
        if (isAnswerSending) {
            return;
        }

        if (AppConfig.hp <= 0) {
            ToastUtil.showShortToast(activity, "体力已耗尽,休息一下再来吧");
            return;
        }

        if (litePalEntity != null) {
            litePalEntity.setAnswerPosition(litePalEntity.getAnswerPosition() + 1);
            litePalEntity.save();
        }

        UMManager.onEvent(UMManager.Event.answers_num);

//        tvAnswer.setTextColor(activity.getResources().getColor(R.color.Color_FFFFFF));
        LoginConfig.setUserAnswerNumber(LoginConfig.getUserAnswerNumber() + 1);

        if (AnswerAdConfig.AD_INTERVAL > 0) {
            if ((litePalEntity.getAnswerPosition() + 1) % AnswerAdConfig.AD_INTERVAL == 0 && (litePalEntity.getAnswerPosition() > (AnswerAdConfig.AD_INTERVAL - 1))) {
                DQLog.e("AnswerAdConfig.getAdType() -> " + AnswerAdConfig.getAdType());
//                if (AnswerAdConfig.getAdType() == AnswerAdConfig.AD_TYPE_INTERSTITIAL) {
//                    DQLog.e("弹出插屏");
//                    AdManager.getInstance().showInterstitialAD(activity);
//                } else if (AnswerAdConfig.getAdType() == AnswerAdConfig.AD_TYPE_FULLSCREEN) {
//                    DQLog.e("弹出全屏视频");
//                    if (AppConfig.getBackMusic()) {
//                        MediaBackManager.getInstance(activity).pause();
//                    }
//                    AdManager.getInstance().showFullscreenVideoAD(activity, new AdManager.OnFullscreenVideoADListener() {
//                        @Override
//                        public void onClosed() {
//                            if (AppConfig.getBackMusic()) {
//                                MediaBackManager.getInstance(activity).start();
//                            }
//                        }
//
//                        @Override
//                        public void onFailed(int i, AdError adError) {
//                            if (AppConfig.getBackMusic()) {
//                                MediaBackManager.getInstance(activity).start();
//                            }
//                        }
//                    });
//                } else if (AnswerAdConfig.getAdType() == AnswerAdConfig.AD_TYPE_REWARD) {
//                    DQLog.e("弹出激励视频");
//                    if (AppConfig.hasNoAd()) {
//                        AppConfig.showNoAdToast(activity);
//                    } else {
//                        if (AppConfig.getBackMusic()) {
//                            MediaBackManager.getInstance(activity).pause();
//                        }
//                        AdManager.getInstance().showRewardVideoAD("", activity, new AdManager.OnRewardVideoADListener() {
//                            @Override
//                            public void onClosed(String orderId) {
//                                if (AppConfig.getBackMusic()) {
//                                    MediaBackManager.getInstance(activity).start();
//                                }
//                            }
//
//                            @Override
//                            public void onReward() {
//                            }
//
//                            @Override
//                            public void onShow(double ecpm) {
//                            }
//
//                            @Override
//                            public void onFailed(int i, AdError adError) {
//                                if (AppConfig.getBackMusic()) {
//                                    MediaBackManager.getInstance(activity).start();
//                                }
//                            }
//                        });
//                    }
//                }
            } else {
                DQLog.e("未满足条件展示广告");
            }
        }

        String answer = "A";
        if (position == 0) {
            answer = "A";
        }
        if (position == 1) {
            answer = "B";
        }
        if (position == 2) {
            answer = "C";
        }
        if (position == 3) {
            answer = "D";
        }

        rightIndex = -1;
        runAdapter.setRightIndex(rightIndex);

        boolean isAnswerRight = dataBean.getAnswer().equals(answer);
        runAdapter.updateAnswerResult(tvAnswer, isAnswerRight);

        if (isAnswerRight) {//答对
            isAnswerSending = true;
            VictoryMusicManager.getInstance(activity).start();
            LoginConfig.setUserAnswerSuccessNumber(LoginConfig.getUserAnswerSuccessNumber() + 1);
            AppConfig.setDayAnswerNumber(AppConfig.getDayAnswerNumber() + 1);

            new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
                @Override
                public void run() {
                    sendAnswerProgress(1, answerType);
                }
            }, 100);
        } else {//答错
            UMManager.onEvent(UMManager.Event.answers_num_error);
            FailureMusicManager.getInstance(activity).start();

            new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
                @Override
                public void run() {
                    if (dialogAnswerFailure != null) {
                        dialogAnswerFailure.dismiss();
                        dialogAnswerFailure = null;
                    }
                    dialogAnswerFailure = new DialogAnswerFailure(activity)
                            .setOnClickLister(new DialogAnswerFailure.OnClickLister() {
                                @Override
                                public void onNext() {
                                    DQLog.e("下一题，重新开始");
                                    sendAnswerProgress(0, answerType);
                                    updateUI();
                                }

                                @Override
                                public void onResurrection() {
                                    DQLog.e("复活保持连对");
                                    isReward = false;
                                    if (AppConfig.hasNoAd()) {
                                        AppConfig.showNoAdToast(activity);
                                        sendAnswerProgress(0, answerType);
                                        updateUI();
                                    } else {
                                        if (AppConfig.getBackMusic()) {
                                            MediaBackManager.getInstance(activity).pause();
                                        }

                                        AdManager.getInstance().showRewardVideoAD("", activity, new AdManager.OnRewardVideoADListener() {
                                            @Override
                                            public void onClosed(String orderId) {
                                                if (AppConfig.getBackMusic()) {
                                                    MediaBackManager.getInstance(activity).start();
                                                }
                                                if (isReward) {
                                                    ToastUtil.showShortToast(activity, "已回复一点体力");
                                                    addOneHp();
                                                    sendAnswerProgress(2, answerType);
                                                    LoginConfig.setUserAnswerSuccessNumber(LoginConfig.getUserAnswerSuccessNumber() + 1);
                                                    AppConfig.setDayAnswerNumber(AppConfig.getDayAnswerNumber() + 1);
                                                } else {
                                                    ToastUtil.showShortToast(activity, "广告未观看完成，回复体力失败");
                                                    sendAnswerProgress(0, answerType);
                                                }
                                                updateUI();
                                            }

                                            @Override
                                            public void onReward() {
                                                isReward = true;
                                            }

                                            @Override
                                            public void onShow(double ecpm) {
                                            }

                                            @Override
                                            public void onFailed(int i, AdError adError) {
                                                if (AppConfig.getBackMusic()) {
                                                    MediaBackManager.getInstance(activity).start();
                                                }
                                                sendAnswerProgress(0, answerType);
                                                updateUI();
                                            }

                                            @Override
                                            public void onTimeout() {
                                                if (AppConfig.getBackMusic()) {
                                                    MediaBackManager.getInstance(activity).start();
                                                }
                                                sendAnswerProgress(0, answerType);
                                                updateUI();
                                            }
                                        });
                                    }
                                }
                            });
                    dialogAnswerFailure.show();
                }
            }, 100);
        }
    }

    private void sendAnswerProgress(int ir, int type) {
        HXCurrencySDK.getInstance().qaAnswerStatisticsReq(ir, type, new HttpUtil.HttpUtilCallback() {
            @Override
            public void onSuccess(int i, String response) {
                DQLog.e("答题结果上报成功：" + response);
                if (activity.isFinishing()) {
                    return;
                }
                QAAnswerStatisticsResp qaAnswerStatisticsResp = JsonUtil.parseObject(response, QAAnswerStatisticsResp.class);
                if (qaAnswerStatisticsResp != null) {
                    answerResult(qaAnswerStatisticsResp);
                } else {
                    DQLog.e("答题结果上报异常");
                }
                isAnswerSending = false;
                updateUI();
            }

            @Override
            public void onFailed(int i, Throwable throwable) {
                DQLog.e("答题结果上报异常：" + throwable.toString());
                isAnswerSending = false;
                updateUI();
            }
        });
    }

    private void answerResult(QAAnswerStatisticsResp qaAnswerStatisticsResp) {
        DQLog.e("答题上报结果：" + qaAnswerStatisticsResp.toString());
        if (activity.isFinishing()) {
            return;
        }

        if (qaAnswerStatisticsResp.getErrorCode() != 0) {
            ToastUtil.showShortToast(activity, qaAnswerStatisticsResp.getErrorMessage());
            return;
        }

        if (qaAnswerStatisticsResp.getUste() == 2 && qaAnswerStatisticsResp.getTb() == 1) {
            new DialogBanned(activity)
                    .setClickLister(new DialogBanned.OnClickLister() {
                        @Override
                        public void onClose() {
                            if (mainActivity.isFinishing()) {
                                return;
                            }
                            mainActivity.finish();
                        }
                    }).show();
            return;
        }

        //扣一点体力
        reduceOneHp();

        LoginConfig.setUserEarningsState(qaAnswerStatisticsResp.getIss());
        LoginConfig.setUserEarningsProgress(qaAnswerStatisticsResp.getIse());
        LoginConfig.setUserEarningsMoney(qaAnswerStatisticsResp.getRwa());

        int ir = qaAnswerStatisticsResp.getIr();
        if (ir == 1) {
            double bat = qaAnswerStatisticsResp.getBat();
            if (bat > LoginConfig.getSaveCash()) {
                isGetSaveCash = true;
            }
            LoginConfig.setSaveCash(bat);
            runBinding.tvSaveCashNum.setText((int) LoginConfig.getSaveCash() + "");
        }

        final double rat = qaAnswerStatisticsResp.getRat();
        if (ir == 1 || ir == 2) {
            LoginConfig.setUserCash(LoginConfig.getUserCash() + rat);

            if (ir == 1) {
                double fcr = qaAnswerStatisticsResp.getFcr();
                UMManager.onEvent(UMManager.Event.answers_num_correct);

                if (dialogAnswerCorrect != null) {
                    dialogAnswerCorrect.dismiss();
                    dialogAnswerCorrect = null;
                }
                dialogAnswerCorrect = new DialogAnswerCorrect(activity)
                        .setMoney(rat)
                        .setOnClickLister(new DialogAnswerCorrect.OnClickLister() {
                            @Override
                            public void onDoubleReceive() {
                                fakeClose(rat);
                            }

                            @Override
                            public void onClose() {
                                if (LoginConfig.getGuideIndex() == 1) {
                                    new DialogGuide(activity).setType(DialogGuide.TYPE_TIPS).setClickLister(new DialogGuide.OnClickLister() {
                                        @Override
                                        public void onNext() {
                                            fakeClose(rat);
                                        }

                                        @Override
                                        public void onGiveUp() {
                                            realClose(isGetSaveCash);
                                        }
                                    }).show();
                                } else if (LoginConfig.getRealCloseTimes() > 0) {
                                    LoginConfig.setRealCloseTimes(LoginConfig.getRealCloseTimes() - 1);
                                    realClose(isGetSaveCash);
                                } else {
                                    if (fcr > 0) {
                                        ArrayList<Double> doubles = new ArrayList<>();
                                        doubles.add(fcr);
                                        doubles.add(1 - fcr);
                                        int lottery = LotteryUtil.lottery(doubles);
                                        if (lottery == 0) {
                                            // 假关闭
                                            UMManager.onEvent(UMManager.Event.SF_falseclose_trigger);
                                            fakeClose(rat);
                                        } else {
                                            realClose(isGetSaveCash);
                                        }
                                    } else {
                                        realClose(isGetSaveCash);
                                    }
                                }
                            }
                        });
                dialogAnswerCorrect.show();
            }
        }
    }

    @Override
    public void onClick(View v) {
        if (ActivityClickUtil.getInstance().isFastClick()) {
            //防止用户快速点击
            return;
        }
        GameMusicManager.getInstance(activity).start();
        if (v.getId() == R.id.imgSetting) {
            SettingActivity.startActivity(activity);
        } else if (v.getId() == R.id.iv_wallet) {
            UMManager.onEvent(UMManager.Event.Click_purse);
            mainActivity.showMe();
        } else if (v.getId() == R.id.layoutHp) {
            // 体力规则
            new DialogHpTip(activity).show();
        } else if (v.getId() == R.id.btnRedBubble1 || v.getId() == R.id.btnRedBubble2 || v.getId() == R.id.btnRedBubble3) {
            UMManager.onEvent(UMManager.Event.Click_BubbleHongbao);
            new DialogRedBubble(activity)
                    .setClickLister(new DialogRedBubble.OnClickLister() {
                        @Override
                        public void onReceive() {
                            LoginConfig.setRedBubbleTimes(LoginConfig.getRedBubbleTimes() + 1);

                            if (LoginConfig.getRedBubbleTimes() >= AppConfig.BUBBLE_TIMES_MAX) {
                                bubbleTime1 = 0;
                                bubbleTime2 = 0;
                                bubbleTime3 = 0;
                                runBinding.btnRedBubble1.clearAnimation();
                                runBinding.btnRedBubble1.setVisibility(View.GONE);
                                runBinding.btnRedBubble2.clearAnimation();
                                runBinding.btnRedBubble2.setVisibility(View.GONE);
                                runBinding.btnRedBubble3.clearAnimation();
                                runBinding.btnRedBubble3.setVisibility(View.GONE);
                            } else {
                                if (v.getId() == R.id.btnRedBubble1) {
                                    bubbleTime1 = System.currentTimeMillis();
                                    Mmkv.setLong("bubbleTime1", bubbleTime1);
                                    runBinding.btnRedBubble1.clearAnimation();
                                    runBinding.btnRedBubble1.setVisibility(View.GONE);
                                } else if (v.getId() == R.id.btnRedBubble2) {
                                    bubbleTime2 = System.currentTimeMillis();
                                    Mmkv.setLong("bubbleTime2", bubbleTime2);
                                    runBinding.btnRedBubble2.clearAnimation();
                                    runBinding.btnRedBubble2.setVisibility(View.GONE);
                                } else if (v.getId() == R.id.btnRedBubble3) {
                                    bubbleTime3 = System.currentTimeMillis();
                                    Mmkv.setLong("bubbleTime3", bubbleTime3);
                                    runBinding.btnRedBubble3.clearAnimation();
                                    runBinding.btnRedBubble3.setVisibility(View.GONE);
                                }
                            }

                            realClose(false);
                        }
                    }).show();
        } else if (v.getId() == R.id.btnSaveCash) {
            new DialogSaveCash(activity)
                    .setClickLister(new DialogSaveCash.OnClickLister() {
                        @Override
                        public void onReceive() {
                            runBinding.ivTipGetBg.setAlpha(0f);
                            runBinding.ivTipNumBg.setAlpha(0f);
                            runBinding.ivTipsIcon.setAlpha(0f);
                            runBinding.tvSaveCashNum.setAlpha(0f);
                            runBinding.tvSaveCashNum.setText((int) LoginConfig.getSaveCash() + "");
                            realClose(false);
                        }
                    }).show();
        } else if (v.getId() == R.id.imgWithdrawal) {
            mainActivity.showMe();
        } else if (v.getId() == R.id.iv_cow_withdrawal) {
            showCashCowDialog();
        } else if (v.getId() == R.id.cl_push) {
            // 互推
            showPushDialog();
        } else if (v.getId() == R.id.cl_daily_task) {
            // 展示每日提现对话框
            showDailyDialog();
        } else if (v.getId() == R.id.cl_invite) {
            // 邀请
            showInviteDialog();
        } else if (v.getId() == R.id.cl_lucky) {
            new DialogLuckyCircle(activity)
                    .setOnLuckAnimationEndListener(new DialogLuckyCircle.OnLuckAnimationEndListener() {
                        @Override
                        public void onLuckAnimationEnd(QAPrize qaPrize, int prizeType, double money) {
                            if (activity.isFinishing()) {
                                return;
                            }
                            DQLog.e("prizeType：" + prizeType + " " + money);
                            new DialogAddCoinResult(activity).setMoney(money).setClickLister(new DialogAddCoinResult.OnClickLister() {
                                @Override
                                public void onReceive() {
                                    realClose(false);
                                }
                            }).show();
                        }
                    }).show();
        } else if (v.getId() == R.id.cl_switch_answer) {
            if (dialogSwitchAnswer != null) {
                dialogSwitchAnswer.dismiss();
                dialogSwitchAnswer = null;
            }
            dialogSwitchAnswer = new DialogSwitchAnswer(activity)
                    .setOnClickLister(new DialogSwitchAnswer.OnClickLister() {
                        @Override
                        public void unlock(AnswerLitePalEntity litePalEntity) {
                            if (litePalEntity.isUnlock()) {
                                AppConfig.setAnswerType(litePalEntity.getAnswerType());
                                new DialogSwitchProgress(activity)
                                        .setDismissLister(new DialogSwitchProgress.OnDismissLister() {
                                            @Override
                                            public void onDismiss() {
                                                ToastUtil.showShortToastCenter(activity, "当前已切换至" + litePalEntity.getTypeName() + "题库");
                                                updateUI();
                                            }
                                        }).show();
                            } else {
                                if (dialogUnlockAnswer != null) {
                                    dialogUnlockAnswer.dismiss();
                                    dialogUnlockAnswer = null;
                                }
                                dialogUnlockAnswer = new DialogUnlockAnswer(activity)
                                        .setOnClickLister(new DialogUnlockAnswer.OnClickLister() {
                                            @Override
                                            public void unlock(boolean isUnlock) {
                                                if (isUnlock) {
                                                    isReward = false;
                                                    if (AppConfig.hasNoAd()) {
                                                        AppConfig.showNoAdToast(activity);
                                                    } else {
                                                        if (AppConfig.getBackMusic()) {
                                                            MediaBackManager.getInstance(activity).pause();
                                                        }
                                                        AdManager.getInstance().showRewardVideoAD("", activity, new AdManager.OnRewardVideoADListener() {
                                                            @Override
                                                            public void onClosed(String orderId) {
                                                                if (AppConfig.getBackMusic()) {
                                                                    MediaBackManager.getInstance(activity).start();
                                                                }
                                                                if (isReward) {
                                                                    litePalEntity.setUnlock(true);
                                                                    litePalEntity.save();
                                                                    ToastUtil.showShortToast(activity, "解锁成功");

                                                                    dialogSwitchAnswer.setList();

                                                                    if (litePalEntity.getAnswerType() == 2) {
                                                                        UMManager.onEvent(UMManager.Event.Unlock_classification1);
                                                                    } else if (litePalEntity.getAnswerType() == 3) {
                                                                        UMManager.onEvent(UMManager.Event.Unlock_classification2);
                                                                    } else if (litePalEntity.getAnswerType() == 4) {
                                                                        UMManager.onEvent(UMManager.Event.Unlock_classification3);
                                                                    } else if (litePalEntity.getAnswerType() == 5) {
                                                                        UMManager.onEvent(UMManager.Event.Unlock_classification4);
                                                                    } else if (litePalEntity.getAnswerType() == 6) {
                                                                        UMManager.onEvent(UMManager.Event.Unlock_classification5);
                                                                    }
                                                                } else {
                                                                    ToastUtil.showShortToast(activity, "未完整观看视频，解锁失败");
                                                                }
                                                            }

                                                            @Override
                                                            public void onReward() {
                                                                isReward = true;
                                                            }

                                                            @Override
                                                            public void onShow(double ecpm) {
                                                            }

                                                            @Override
                                                            public void onFailed(int i, AdError adError) {
                                                                if (AppConfig.getBackMusic()) {
                                                                    MediaBackManager.getInstance(activity).start();
                                                                }
                                                            }

                                                            @Override
                                                            public void onTimeout() {
                                                                if (AppConfig.getBackMusic()) {
                                                                    MediaBackManager.getInstance(activity).start();
                                                                }
                                                            }
                                                        });
                                                    }
                                                }
                                            }
                                        });
                                dialogUnlockAnswer.show();
                            }
                        }
                    });
            dialogSwitchAnswer.show();
        } else if (v.getId() == R.id.cl_sign) {
            getSignData();
        }
    }

    private void showGuideDialog() {
        if (LoginConfig.getGuideIndex() == 0) {
            new DialogGuide(activity).show();
        } else {
            showSurpriseDialog();
        }
    }

    private void showPushDialog() {
        new PushDialogFragment().show(getChildFragmentManager(), "push_dialog");
    }

    private void showDailyDialog() {
        new DialogDailyWithdrawal(activity)
                .setClickLister(new DialogDailyWithdrawal.OnClickLister() {
                    @Override
                    public void onWithdrawal(double coin) {
                        if (AppConfig.hasNoAd()) {
                            AppConfig.showNoAdToast(activity);
                        } else {
                            if (AppConfig.getBackMusic()) {
                                MediaBackManager.getInstance(activity).pause();
                            }
                            AdManager.getInstance().showRewardVideoAD("每日提现", activity, new AdManager.OnRewardVideoADListener() {
                                @Override
                                public void onClosed(String orderId) {
                                    if (AppConfig.getBackMusic()) {
                                        MediaBackManager.getInstance(activity).start();
                                    }
                                    if (isReward) {
                                        AppConfig.setTotalPiggy(AppConfig.getTotalPiggy() - (long) coin);
                                        int extractTimes = AppConfig.getExtractTimes();
                                        if (extractTimes == 0) {
                                            UMManager.onEvent(UMManager.Event.receive_Dailyprize_1);
                                        } else if (extractTimes == 1) {
                                            UMManager.onEvent(UMManager.Event.receive_Dailyprize_2);
                                        }
                                        AppConfig.setExtractTimes(extractTimes + 1);
                                        LoginConfig.setUserCash(LoginConfig.getUserCash() + coin);

                                        new DialogGoWithdrawal(activity).setType(1).setCoin(coin).setClickLister(new DialogGoWithdrawal.OnClickLister() {
                                            @Override
                                            public void onWithdrawal() {
                                                mainActivity.showMe();
                                            }
                                        }).show();
                                    } else {
                                        ToastUtil.showShortToast(activity, "未完整观看视频，提取失败");
                                    }
                                }

                                @Override
                                public void onReward() {
                                    isReward = true;
                                }

                                @Override
                                public void onShow(double ecpm) {
                                }

                                @Override
                                public void onFailed(int i, AdError adError) {
                                    if (AppConfig.getBackMusic()) {
                                        MediaBackManager.getInstance(activity).start();
                                    }
                                }

                                @Override
                                public void onTimeout() {
                                    if (AppConfig.getBackMusic()) {
                                        MediaBackManager.getInstance(activity).start();
                                    }
                                }
                            });
                        }
                    }
                }).show();
    }

    private void getSignData() {
        HXCurrencySDK.getInstance().getSignConfig(new HttpUtil.HttpUtilCallback() {
            @Override
            public void onSuccess(int i, String s) {
                DQLog.e("获取签到列表：" + s);
                if (activity.isFinishing()) {
                    return;
                }
                SignConfigResp signConfigResp = JsonUtil.parseObject(s, SignConfigResp.class);
                if (signConfigResp.getErrorCode() == 0) {//获取成功
                    new DialogSign(activity)
                            .setList(signConfigResp.getSl())
                            .setTodayPos(signConfigResp.getCd())
                            .setTodaySignState(signConfigResp.getTs() != 0)
                            .setOnClickLister(new DialogSign.OnClickLister() {
                                @Override
                                public void onSign() {
                                    if (signConfigResp.getTs() != 0) {
                                        ToastUtil.showShortToastCenter(activity, "今日已签到，无需重复签到");
                                        return;
                                    }

                                    isReward = false;
                                    if (AppConfig.hasNoAd()) {
                                        AppConfig.showNoAdToast(activity);
                                    } else {
                                        if (AppConfig.getBackMusic()) {
                                            MediaBackManager.getInstance(activity).pause();
                                        }
                                        AdManager.getInstance().showRewardVideoAD("", activity, new AdManager.OnRewardVideoADListener() {
                                            @Override
                                            public void onClosed(String orderId) {
                                                if (AppConfig.getBackMusic()) {
                                                    MediaBackManager.getInstance(activity).start();
                                                }
                                                if (isReward) {
                                                    sign();
                                                } else {
                                                    ToastUtil.showShortToast(activity, "广告未观看完成，签到失败");
                                                }
                                            }

                                            @Override
                                            public void onReward() {
                                                isReward = true;
                                            }

                                            @Override
                                            public void onShow(double ecpm) {
                                            }

                                            @Override
                                            public void onFailed(int i, AdError adError) {
                                                if (AppConfig.getBackMusic()) {
                                                    MediaBackManager.getInstance(activity).start();
                                                }
                                            }

                                            @Override
                                            public void onTimeout() {
                                                if (AppConfig.getBackMusic()) {
                                                    MediaBackManager.getInstance(activity).start();
                                                }
                                            }
                                        });
                                    }
                                }

                                @Override
                                public void onClose() {
                                }
                            }).show();
                }
            }

            @Override
            public void onFailed(int i, Throwable throwable) {
                DQLog.e("签到列表获取异常：" + throwable.getMessage());
            }
        });
    }

    private void showSurpriseDialog() {
        if (activity.isFinishing()) {
            return;
        }

        if (LoginConfig.getSurpriseTimes() >= AppConfig.SURPRISE_TIMES_MAX) {
            return;
        }
        LoginConfig.setSurpriseTimes(LoginConfig.getSurpriseTimes() + 1);

        new DialogRedBubble(activity)
                .setType(DialogRedBubble.TYPE_SURPRISE)
                .setClickLister(new DialogRedBubble.OnClickLister() {
                    @Override
                    public void onReceive() {
                        realClose(false);
                    }
                }).show();
    }

    private void showInviteDialog() {
        // 展示邀请对话框
        new DialogInvite(activity).setClickLister(new DialogInvite.OnClickLister() {
            @Override
            public void onInvite(String inviteCode) {
                UMManager.onEvent(UMManager.Event.Click_Invite);
                new DialogShare(activity).setInviteCode(inviteCode).show();
            }
        }).show();
    }

    private void showCashCowDialog() {
        new DialogCashCow(activity)
                .setClickLister(new DialogCashCow.OnClickLister() {
                    @Override
                    public void onIntroduce() {
                        IntroduceActivity.startActivity(activity);
                    }
                }).show();
    }

    private void sign() {
        HXCurrencySDK.getInstance().sign(new HttpUtil.HttpUtilCallback() {
            @Override
            public void onSuccess(int i, String s) {
                DQLog.e("签到成功:" + s);
                if (activity.isFinishing()) {
                    return;
                }
                SignResp signResp = JsonUtil.parseObject(s, SignResp.class);
                if (signResp != null) {
                    if (signResp.getErrorCode() == 0) {
                        LoginConfig.setTodaySignState(1);
                        if (signResp.getRt() == 6) {
                            LoginConfig.setUserCash(LoginConfig.getUserCash() + signResp.getSr());
                        }
                        new DialogAddCoinResult(activity)
                                .setType(DialogAddCoinResult.TYPE_SIGN)
                                .setMoney(signResp.getSr())
                                .setClickLister(new DialogAddCoinResult.OnClickLister() {
                                    @Override
                                    public void onReceive() {
                                        if (signResp.getRt() == 4) {//提现机会
                                            mainActivity.showMe();
                                        }
                                        updateUI();
                                    }
                                }).show();
                    } else {
                        String errorMessage = signResp.getErrorMessage();
                        if (errorMessage.isEmpty()) {
                            errorMessage = "错误码=" + signResp.getErrorCode();
                        }
                        ToastUtil.showShortToast(activity, "签到失败：" + errorMessage);
                    }
                } else {
                    ToastUtil.showShortToast(activity, "签到失败");
                }
            }

            @Override
            public void onFailed(int i, Throwable throwable) {
                DQLog.e("签到失败:" + throwable.getMessage());
                ToastUtil.showShortToast(activity, "签到失败：" + throwable.getMessage());
            }
        });
    }

    /**
     * 根据ecpm发放奖励（不是翻倍）
     *
     * @param sc
     * @param pid
     * @param ot
     * @param rat
     * @param prizeType
     * @param ecpm
     */
    private void doubleReceive(int sc, int pid, int ot, double rat, int prizeType, double ecpm, String orderId) {
        DQLog.e("领取额外奖励: sc=" + sc + ", rat=" + rat + ", ecpm=" + ecpm);
        if (dialogLoading == null) {
            dialogLoading = new BaseAdDialogLoading(activity).setContent("正在领取奖励...");
        }
        dialogLoading.show();
        HXCurrencySDK.getInstance().qaDoubleRewardReq(sc, pid, ot, rat, ecpm, orderId, new HttpUtil.HttpUtilCallback() {
            @Override
            public void onSuccess(int i, String response) {
                DQLog.e("领取额外奖励成功：" + response);
                if (activity.isFinishing()) {
                    return;
                }
                if (dialogLoading != null) {
                    dialogLoading.dismiss();
                    dialogLoading = null;
                }
                QADoubleRewardResp qaDoubleRewardResp = JsonUtil.parseObject(response, QADoubleRewardResp.class);
                if (qaDoubleRewardResp != null) {
                    if (qaDoubleRewardResp.getErrorCode() == 0) {
                        LoginConfig.setUserCash(LoginConfig.getUserCash() + qaDoubleRewardResp.getDa());
                        //更新存钱罐
                        boolean isSaveCash = qaDoubleRewardResp.getBat() > LoginConfig.getSaveCash();
                        LoginConfig.setSaveCash(qaDoubleRewardResp.getBat());
                        runBinding.tvSaveCashNum.setText((int) LoginConfig.getSaveCash() + "");

                        showExtraDialog(qaDoubleRewardResp.getDa(), isSaveCash);
                    } else {
                        String errorMessage = qaDoubleRewardResp.getErrorMessage();
                        if (errorMessage.isEmpty()) {
                            errorMessage = "错误码=" + qaDoubleRewardResp.getErrorCode();
                        }
                        ToastUtil.showShortToast(activity, "领取额外奖励失败：" + errorMessage);
                    }
                } else {
                    ToastUtil.showShortToast(activity, "领取额外奖励失败");
                }
                updateUI();
            }

            @Override
            public void onFailed(int i, Throwable throwable) {
                if (activity.isFinishing()) return;
                if (dialogLoading != null) {
                    dialogLoading.dismiss();
                    dialogLoading = null;
                }
                DQLog.e("领取额外奖励失败：" + throwable.getMessage());
                ToastUtil.showShortToast(activity, "领取额外奖励失败：" + throwable.getMessage());
                GoldMusicManager.getInstance(activity).start();
                updateUI();
            }
        });
    }

    private void showExtraDialog(double money, boolean isSaveCash) {
        new DialogAddCoinResult(activity).setType(DialogAddCoinResult.TYPE_EXTRA).setMoney(money).setClickLister(new DialogAddCoinResult.OnClickLister() {
            @Override
            public void onReceive() {
                if (activity.isFinishing()) return;
                if (isSaveCash) {
                    runBinding.lottieDoubleGoldAnim.setVisibility(View.VISIBLE);
                    runBinding.lottieDoubleGoldAnim.playAnimation();
                    saveCountTime = 0;//显示储存罐上面的消息框
                } else {
                    runBinding.lottieGoldAnim.setVisibility(View.VISIBLE);
                    runBinding.lottieGoldAnim.playAnimation();
                }

                updateUI();
            }
        }).show();
    }

    private void fakeClose(double rat) {
        DQLog.e("ecpm翻倍领取: " + rat);
        final double[] ep = {0.0};
        isReward = false;
        if (AppConfig.hasNoAd()) {
            AppConfig.showNoAdToast(activity);
            updateUI();
        } else {
            if (AppConfig.getBackMusic()) {
                MediaBackManager.getInstance(activity).pause();
            }
            AdManager.getInstance().showRewardVideoAD("ecpm翻倍领取", String.valueOf(rat), activity, new AdManager.OnRewardVideoADListener() {
                @Override
                public void onClosed(String orderId) {
                    if (AppConfig.getBackMusic()) {
                        MediaBackManager.getInstance(activity).start();
                    }
                    if (isReward) {
                        doubleReceive(11, -1, 1, rat, 7, ep[0], orderId);
                    } else {
                        ToastUtil.showShortToast(activity, "未完整观看视频，领取失败");
                        updateUI();
                    }
                }

                @Override
                public void onReward() {
                    isReward = true;
                }

                @Override
                public void onShow(double ecpm) {
                    ep[0] = ecpm;
                    UMManager.onEvent(UMManager.Event.SF_IV_success);
                }

                @Override
                public void onFailed(int i, AdError adError) {
                    UMManager.onEvent(UMManager.Event.SF_IV_fail);
                    if (AppConfig.getBackMusic()) {
                        MediaBackManager.getInstance(activity).start();
                    }
                    updateUI();
                }

                @Override
                public void onTimeout() {
                    UMManager.onEvent(UMManager.Event.SF_IV_fail);
                    if (AppConfig.getBackMusic()) {
                        MediaBackManager.getInstance(activity).start();
                    }
                    updateUI();
                }
            });
        }
    }

    private void realClose(boolean isSaveCash) {
        GoldMusicManager.getInstance(activity).start();
        if (isSaveCash) {
            runBinding.lottieDoubleGoldAnim.setVisibility(View.VISIBLE);
            runBinding.lottieDoubleGoldAnim.playAnimation();
            saveCountTime = 0;//显示储存罐上面的消息框
        } else {
            runBinding.lottieGoldAnim.setVisibility(View.VISIBLE);
            runBinding.lottieGoldAnim.playAnimation();
        }

        updateUI();
    }

    private void watchVideo() {
        isReward = false;
        if (AppConfig.hasNoAd()) {
            AppConfig.showNoAdToast(activity);
        } else {
            if (AppConfig.getBackMusic()) {
                MediaBackManager.getInstance(activity).pause();
            }
            AdManager.getInstance().showRewardVideoAD("", activity, new AdManager.OnRewardVideoADListener() {
                @Override
                public void onClosed(String orderId) {
                    if (AppConfig.getBackMusic()) {
                        MediaBackManager.getInstance(activity).start();
                    }
                    if (isReward) {
                        addCoin(orderId);
                    } else {
                        ToastUtil.showShortToast(activity, "未完整观看视频，领取失败");
                    }
                }

                @Override
                public void onReward() {
                    isReward = true;
                }

                @Override
                public void onShow(double ecpm) {
                }

                @Override
                public void onFailed(int i, AdError adError) {
                    if (AppConfig.getBackMusic()) {
                        MediaBackManager.getInstance(activity).start();
                    }
                }

                @Override
                public void onTimeout() {
                    if (AppConfig.getBackMusic()) {
                        MediaBackManager.getInstance(activity).start();
                    }
                }
            });
        }
    }

    private void addCoin(String orderId) {
        HXCurrencySDK.getInstance().qaWatchVideo(2, 888, orderId, new HttpUtil.HttpUtilCallback() {
            @Override
            public void onSuccess(int i, String response) {
                DQLog.e("答题小助手 看视频补充红包券成功：" + response);
                if (activity.isFinishing()) {
                    return;
                }
                QAWatchVideoResp qaWatchVideoResp = JsonUtil.parseObject(response, QAWatchVideoResp.class);
                if (qaWatchVideoResp != null) {
                    if (qaWatchVideoResp.getErrorCode() == 0) {
                        if (activity.isFinishing()) {
                            return;
                        }

                        double ra = qaWatchVideoResp.getRa();
                        LoginConfig.setUserCash(LoginConfig.getUserCash() + ra);
                        updateUI();
                        UMManager.onEvent(UMManager.Event.WithdrawalsHongbao_Receive);
                        new DialogAddCoinResult(activity).setMoney(ra).setClickLister(new DialogAddCoinResult.OnClickLister() {
                            @Override
                            public void onReceive() {
                                realClose(false);
                            }
                        }).show();
                    } else {
                        String errorMessage = qaWatchVideoResp.getErrorMessage();
                        if (errorMessage.isEmpty()) {
                            errorMessage = "错误码=" + qaWatchVideoResp.getErrorCode();
                        }
                        ToastUtil.showShortToast(activity, "答题小助手 看视频补充红包券失败：" + errorMessage);
                    }
                } else {
                    ToastUtil.showShortToast(activity, "答题小助手 看视频补充红包券失败");
                }
            }

            @Override
            public void onFailed(int i, Throwable throwable) {
                DQLog.e("答题小助手 看视频补充红包券失败：" + throwable.getMessage());
                ToastUtil.showShortToast(activity, "答题小助手 看视频补充红包券失败：" + throwable.getMessage());
            }
        });
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

        if (dialogAddCoinResult != null) {
            dialogAddCoinResult.dismiss();
            dialogAddCoinResult = null;
        }
        if (dialogUnlockAnswer != null) {
            dialogUnlockAnswer.dismiss();
            dialogUnlockAnswer = null;
        }
        if (dialogSwitchAnswer != null) {
            dialogSwitchAnswer.dismiss();
            dialogSwitchAnswer = null;
        }
        if (dialogAnswerCorrect != null) {
            dialogAnswerCorrect.dismiss();
            dialogAnswerCorrect = null;
        }
        if (dialogAnswerFailure != null) {
            dialogAnswerFailure.dismiss();
            dialogAnswerFailure = null;
        }
    }
}